import math
import os
import xml.dom.minidom
import cv2
import utils
import numpy as np




# ======================================================================函数功能
# 将最大框外的边缘缩减一半

# ======================================================================参数设置begin
file_dir = './1/'  # 源文件路径
produce_dir = './2/'  # 输出文件路径
# ======================================================================参数设置end

names = []
a = os.scandir(file_dir)

for files in os.scandir(file_dir):
    if files.name[-1] == 'l':
        names.append(files.name)
for file_name in names:
    img = cv2.imread(file_dir + file_name[:-4] + '.jpg')
    img_cp = img.copy()
    # img_cp = img[0:100, 0:200]
    i_h, i_w, _ = img.shape
    locations = utils.ReadXml(file_dir + file_name)
    # cv2.namedWindow("src", cv2.WINDOW_NORMAL)
    for i in range(len(locations)):
        cv2.rectangle(img_cp, (int(locations[i][0]), int(locations[i][1])),
                      (int(locations[i][2]), int(locations[i][3])), (255, 0, 0), 3)
    cv2.imshow('src', img_cp)
    # cv2.waitKey(0)
    locations = np.array(locations)
    x_min = int(min(locations[:, 0]))
    y_min = int(min(locations[:, 1]))
    x_max = int(max(locations[:, 2]))
    y_max = int(max(locations[:, 3]))

    img_new = img[int(y_min / 2):math.ceil((y_max + i_h) / 2), int(x_min / 2):math.ceil((x_max + i_w) / 2)]
    revise = np.array([int(x_min / 2), int(y_min / 2), int(x_min / 2), int(y_min / 2)])
    locations_new = [produce_dir + "\\" + file_name]
    for location in locations:
        location_arr = location[:-1].astype(np.int32)
        location_arr -= revise
        location[:-1] = location_arr
        # locations = locations.tolist()
        # locations.append(label)
        locations_new.append(location)
    utils.WriteXml(locations_new, int((x_max + i_w) / 2) - int(x_min / 2), int((y_max + i_h) / 2) - int(y_min / 2))
    cv2.imwrite(produce_dir + file_name[:-4] + '.jpg', img_new)

for i in range(1, len(locations_new)):
    cv2.rectangle(img_new, (int(locations_new[i][0]), int(locations_new[i][1])),
                  (int(locations_new[i][2]), int(locations_new[i][3])), (255, 0, 0), 3)
# cv2.namedWindow("new", cv2.WINDOW_NORMAL)
cv2.imshow('new', img_new)
cv2.waitKey(0)
